const app = getApp();
Page({
  data: {
    videoFilePaths: [], // 存储视频文件路径
    uploadTasks: [], // 上传任务
    uploading: false, // 是否正在上传
  },

  onLoad: function () {
    this.uuid = `${Date.now()}-${Math.floor(Math.random() * 100000000)}`;
    this.index = 0;
    const initList = app.globalData.videoList || [];
    this.setData({
      videoFilePaths: initList.map((filePath) => {
        return { filePath, progress: 0 };
      }),
    });
  },
  siginUploadVideo: function (event) {
    const filePath = event.currentTarget.dataset.filePath;
    console.log(filePath, event);
    this.uploadVideo(filePath);
  },
  uploadVideo: function (filePath) {
    const HOST_IP = 'nyjk.up.jd.com';
    const UPLOAD_URL = `http://${HOST_IP}:3000/upBigFile`;
    this.index = this.index + 1;
    return new Promise((resolve, reject) => {
      const uploadTask = wx.uploadFile({
        url: UPLOAD_URL, // 替换为你的上传接口
        filePath: filePath,
        name: 'file', // 服务器端接收文件的字段名
        formData: { identifier: this.uuid, index: this.index },
        timeout: 1000 * 60 * 10,
        header: { 'Content-type': 'multipart/form-data' },
        success: resolve,
        fail: reject,
        complete: () => {
          this.checkUploadCompletion();
        },
      });
      uploadTask.onProgressUpdate((res) => {
        console.log('Upload progress', res.progress);
        this.updateProgress(filePath, res.progress);
        if (res.progress >= 100) {
          console.log('=============resove');
          resolve();
        }
      });
      this.data.uploadTasks.push({ filePath, uploadTask });
    });
  },

  uploadSelectedVideos: async function () {
    if (this.data.uploading) return;
    this.setData({ uploading: true });
    wx.setKeepScreenOn({ keepScreenOn: true });
    for (const item of this.data.videoFilePaths) {
      try {
        const { filePath, progress } = item;
        if (progress !== 100) {
          console.log('=================1');
          await this.uploadVideo(filePath);
        }
      } catch (error) {
        console.log('上传失败');
      }
    }
    console.log('uploading=false');
    wx.setKeepScreenOn({ keepScreenOn: false });
    this.setData({ uploading: false });
  },

  updateProgress: function (filePath, progress) {
    const index = this.data.videoFilePaths.findIndex((item) => item.filePath === filePath);
    if (index !== -1) {
      this.setData({
        [`videoFilePaths[${index}].progress`]: progress,
      });
    }
  },

  checkUploadCompletion: function () {
    const completed = this.data.uploadTasks.every((task) => task.uploadTask === null || task.uploadTask.progress === 100);
    if (completed) {
      this.setData({ uploading: false });
      console.log('All uploads completed');
    }
  },
});
